<template>
  <view class="order-container">
    <h3 class="order-title">确认订单</h3>
    
    <view class="address-section" @click="changeaddress">
      <text class="section-title">收货地址</text>
      <view class="address-content">
        <text>

        <view v-for="item in addressselect" :key="item._id" class="address-item">
        <view class="address-info">
          <text class="address-text">
            <text class="highlight">收货人{{ item.consignee }}</text>
            <text class="highlight">联系方式{{ item.phone }}</text>
          </text>
          <text class="address-detail">
            所在地区：{{ item.region }}详细地址：{{ item.address }}门牌号：{{ item.doorNumber }}
          </text>
        </view>
      </view>

        </text>
      </view>
	  <view class="address-content">
	    <view v-if="addressselect.length > 0">
	      <view v-for="item in addressselect" :key="item._id" class="address-item">
	        <view class="address-info">
	          <text class="address-text">
	            <text class="highlight">收货人: {{ item.consignee }}</text>
	            <text class="highlight">联系方式: {{ item.phone }}</text>
	          </text>
	          <text class="address-detail">
	            所在地区: {{ item.region }} 
	            详细地址: {{ item.address }} 
	            门牌号: {{ item.doorNumber }}
	          </text>
	        </view>
	      </view>
	    </view>
	    <view v-else class="empty-address">
	      <text>暂无收货地址，请添加</text>
	    </view>
	  </view>
    </view>
    
    <view class="product-list">
      <view v-for="item in a" :key="item._id" class="product-item">
        <image class="product-image" :src="item.imgUrl" mode="aspectFill"></image>
        <view class="product-info">
          <text class="product-name">{{ item.name }}</text>
          <view class="price-container">
            <text class="current-price">¥{{ item.price }}</text>
            <text class="old-price">¥{{ item.oldPrice }}</text>
          </view>
          <text class="sales">数量 {{ item.count }}份</text>
        </view>
      </view>
    </view>
    
    <view class="total-section">
      <text class="total-text">实际支付金额：</text>
      <text class="total-amount">¥{{ calculateTotal() }}</text>
    </view>
    
    <button class="submit-button" @click="showPaymentDialog">提交订单</button>
  </view>
</template>

<script>
	import config from "@/Config.js";
export default {
  data() {
    return {
      a: [],
      username:"",
      address:[],
      addressselect:[],
      token:""
    }
  },
  onShow() {
   this.query()
    this.getaddress()
    // 优先使用选中的地址，如果没有则使用第一个地址
   setTimeout(() => {
       const selectedAddress = uni.getStorageSync('producted');
       console.log('从缓存获取的地址:', selectedAddress);
       console.log('当前地址列表:', this.address);
       
       // 确保addressselect始终是数组
       if (selectedAddress) {
         this.addressselect = Array.isArray(selectedAddress) ? selectedAddress : [selectedAddress];
       } else if (this.address && this.address.length > 0) {
         this.addressselect = [this.address[0]]; 
       } else {
         this.addressselect = [];
         console.warn('没有可用的地址数据');
       }
       
       console.log('最终addressselect:', this.addressselect);
       this.$forceUpdate();
     }, 800); // 增加延迟时间
	  
  },
  onLoad() {
    this.query(),
    this.haha()
    
  },
  methods: {
    changeaddress() {
      uni.navigateTo({
        url:"/pages/changeaddress/changeaddress"
      });
    },
    getaddress() {
      uni.request({
        url: config.config+"/address",
        method: "GET",
        header: {
          "Content-Type": "application/json"
        },
        success: (res) => {
          console.log("请求成功:", res);
          // 获取本地token
          this.token = uni.getStorageSync("token");
          // 过滤数据
          this.address = res.data.filter(item => item.token === this.token);
        }
      });
    },
    haha(){
    this.token = uni.getStorageSync('token')
      uni.request({
        url:config.config+ '/user',
        method: 'GET',
        success: (res) => {
          console.log('请求成功:', res)
          res.data.forEach(element => {
            if(element.id== this.token){
                this.username=element.username
            }
              
          });
          
        }
      })
    },

    query() {
      this.a = uni.getStorageSync('a') || [];
    },
    calculateTotal() {
      return this.a.reduce((sum, item) => sum + (item.price * item.count), 0).toFixed(2);
    },
    showPaymentDialog() {
      uni.showModal({
        title: '确认支付',
        content: `确认支付 ¥${this.calculateTotal()} 吗？`,
        confirmText: '确认支付',
        cancelText: '取消支付',
        success: (res) => {
          if (res.confirm) {
            this.confirmPayment();


          } else if (res.cancel) {
            this.cancelPayment();
          }
        }
      });
    },
    confirmPayment() {
      uni.showToast({
        title: '支付成功',
        icon: 'success',
        duration: 2000
      });

       const now = new Date();
  const currentTime = `${now.getFullYear()}-${(now.getMonth() + 1)
  .toString().padStart(2, '0')}-${now.getDate().toString().
  padStart(2, '0')} ${now.getHours().toString().
  padStart(2, '0')}:${now.getMinutes().toString().
  padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`;

   // 准备订单数据（包含时间戳）
 
   const orderData = {
     items: this.a,
     total: this.calculateTotal(),
     username: this.username,
     token: this.token,
     createTime: currentTime,
     address: this.addressselect
   };
 
   // 保存当前组件的this引用
   const that = this;
   
   uni.request({
     url: config.config+'/indent',
     method: 'POST',
     data: orderData,
     header: {
       'Content-Type': 'application/json'
     },
     success: function(res) {  // 使用普通函数时需要用that
       console.log('请求成功', res.data);
       that.a = [];  // 使用that替代this
       uni.setStorageSync('a', that.a);
       uni.switchTab({
         url: '/pages/dingdan/dingdan'
       });
     },
     fail: function(err) {
       console.error('请求失败', err);
     }
   });

    
    },
    cancelPayment() {
      uni.showToast({
        title: '已取消支付',
        icon: 'none',
        duration: 2000
      });
    }
  }
}
</script>

<style>
/* 全局样式 */
.order-container {
  padding: 20rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

/* 订单标题 */
.order-title {
  font-size: 36rpx;
  font-weight: bold;
  text-align: center;
  margin: 20rpx 0;
  color: #333;
}

/* 地址区域 */
.address-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.address-content {
  font-size: 26rpx;
  color: #666;
}

/* 商品列表 */
.product-list {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 0 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.product-item {
  display: flex;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.product-item:last-child {
  border-bottom: none;
}

.product-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 28rpx;
  color: #333;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.price-container {
  display: flex;
  align-items: center;
  margin-top: 10rpx;
}

.current-price {
  font-size: 32rpx;
  color: #ff4d4f;
  font-weight: bold;
  margin-right: 10rpx;
}

.old-price {
  font-size: 24rpx;
  color: #999;
  text-decoration: line-through;
}

.sales {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

/* 总金额 */
.total-section {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.total-text {
  font-size: 28rpx;
  color: #333;
}

.total-amount {
  font-size: 32rpx;
  color: #ff4d4f;
  font-weight: bold;
  margin-left: 10rpx;
}

/* 提交按钮 */
.submit-button {
  background-color: #ff4d4f;
  color: #fff;
  border: none;
  border-radius: 50rpx;
  font-size: 32rpx;
  height: 80rpx;
  line-height: 80rpx;
  margin: 20rpx 0;
  width: 100%;
}

.submit-button:active {
  opacity: 0.8;
}
</style>